import Fun from "./index";
var phone_bill_recharge_type = true; //话费充值 提示弹窗

async function unfinishedTaskFn(data) {
  let _isMissionURL = window.location.href.indexOf("/usr/missionCenter?") > -1; //是否位于任务中心页
  window._activePageURL = (!_isMissionURL ? window.location.href : sessionStorage.getItem("beforeBindMobilePage")) || window.location.href;
  // promises，数组格式
  const promises = [
    bindMobile(data),
    bindInviter(data),
    bindRealName(data),
    setAddress(data),
    uploadVideo(data),
    levelCompel(data),
    phoneBillRecharge(data),
    signContract(data),
    carBind(data)
  ];
  const results = await Promise.allSettled(promises); //并行执行，并返回包含所有承诺结果的对象数组
  let validResults = []; //当前符合条件的集合
  let activeResults = []; //当前符合条件并且处于某个条件处理的页面内，不做处理
  for (let i = 0; i < results.length; i++) {
    const result = results[i];
    if (result.status === "rejected" && result.reason.type) {
      if (result.reason.type == "active") {
        activeResults.push(result);
      } else {
        validResults.push(result);
      }
    }
  }

  if (validResults.length === 0 && activeResults.length === 0) {
    if (window.location.href.indexOf("/usr/missionCenter?") > 0) {
      window.location.href = window._activePageURL;
    }
    return;
  }

  if (_isMissionURL || activeResults.length > 0) {
    return validResults; //当前处理任务中心页或者某个条件的页面内，return处理
  }

  if (validResults.length >= 2) {
    if (!_isMissionURL) {
      if (activeResults.length === 0) {
        // alert(window.location.href)
        let _sURL = sessionStorage.getItem("beforeBindMobilePage") || null;
        if (!_sURL) sessionStorage.setItem("beforeBindMobilePage", window.location.href); //记录绑定手机跳转前页面路径
      }
      window.__lendApp__.$router.push(Fun.getUrl("missionCenter")); //如果有两个或两个以上promist符合条件，则执行跳转到 任务中心列表页：
    }
    return validResults;
  }
  validResults.forEach(result => {
    redirectToPage(result.reason.type);
  });
}

function redirectToPage(type) {
  let _isMissionURL = window.location.href.indexOf("/usr/missionCenter?") > -1; //是否位于任务中心页
  let _activePageURL = (!_isMissionURL ? window.location.href : sessionStorage.getItem("beforeBindMobilePage")) || window.location.href;
  let callbackUrl = "";
  let validate_page = JSON.parse(sessionStorage.getItem('validate_page'))||{};
  let name,
    params = {},
    query = {};
  switch (type) {
  case "bindMobile":
    if (_activePageURL.indexOf("/signPage/") > -1) {
      query.from = "signPage";
    }
    name = "editmobile";
    break;
  case "bindInviter":
    name = "Inviter";
    break;
  case "bindRealName":
    name = "personBank";
    query.from = "bindRealName";
    callbackUrl = _activePageURL.includes("/personBank") ? `${Fun.getSiteRoot()}/addons/yun_shop/?menu#/home?i=${Fun.getKeyByI()}&mid=${Fun.getKeyByMid()}` : _activePageURL;
    window.__lendApp__.$store.commit("setCallback", callbackUrl); // 设置回调 URL。
    break;
  case "setAddress":
    window.__lendApp__.$dialog.confirm({ message: `请设置默认地址`, confirmButtonText: "去设置", showCancelButton: false }).then(() => {
      return window.__lendApp__.$router.push(Fun.getUrl("address"));
    });
    break;
  case "uploadVideo":
    name = "releaseVideo";
    query.from = "validate";
    break;
  case "levelCompel":
    name = "levelCompel";
    break;
  case "phoneBillRecharge":
    window.__lendApp__.$dialog.confirm({ message: `${validate_page.phone_bill_recharge_member.tips}?`, confirmButtonText: '确定'})
      .then(() => {
        phone_bill_recharge_type = false;
        if(validate_page.phone_bill_recharge_member.type == 'copy'){
          // 绑卡，充值
          let rechargeUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/recharge_phone_bill/recharge_phone_bill/"+ encodeURIComponent(validate_page.phone_bill_recharge_member.url) +"?i=" + Fun.getKeyByI();
          return window.location.href = rechargeUrl;
        }else{
          return window.location.href = validate_page.phone_bill_recharge_member.url;// 开卡
        }
      }).catch(() => {
        phone_bill_recharge_type = false;
      });
    break;
  case "signContract":
    window.__lendApp__.$dialog.confirm({ message: `您有合同未签署完成，请前往签署合同`, confirmButtonText: '确定'})
      .then(() => {
        let cid = validate_page.shop_contract.cid || 0;
        let signUrl = Fun.getSiteRoot() + "/addons/yun_shop/?menu#/contractList?status=3&i=" + Fun.getKeyByI();
        if(cid) signUrl = signUrl + '&cid=' + cid;
        return window.location.href = signUrl;
      }).catch(() => {
        window.__lendApp__.$router.replace(Fun.getUrl("home"));
      });
    break;
  case "carBind":
    name = "carBind";
    break
  }
  if (name) window.__lendApp__.$router.replace(Fun.getUrl(name, params, query));
}

// 判断当前页面是否需要进入邀请页，以及判断用户是否已经填写过邀请人和绑定手机
// 如果未填写或未绑定，则会跳转到邀请页。
function bindInviter(data) {
  if (data.invite_page !== 1) {
    return Promise.resolve(); //没有开启，resolve
  }
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  const ignoredPages = ["input_visit", "member/editmobile", "inviterAndPhone"]; // 忽略某些页面，不需要进入邀请页或者已在邀请相关页面内
  const requiresInvitation = !ignoredPages.some(page => window.location.href.includes(page));
  if (window.location.href.indexOf("/inviter?") > -1 || !requiresInvitation) {
    return Promise.reject({ type: "active", name: "填写邀请码" });
  }
  // 判断用户是否已有邀请码
  if ((data.is_invite !== 1 && !window.__lendApp__.$store.state.is_Inviter) || data.invite_mobile !== 1) {
    return Promise.reject({ type: "bindInviter", name: "填写邀请码", icon: "icon-fontclass-yaoqingma", color: "#FF3835" }); // 需要跳转到邀请页面
  }
  return Promise.resolve();
}

// 绑定手机
async function bindMobile(data) {
  let { is_bind_mobile, bind_mobile_page } = data;
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if (is_bind_mobile === 0) {
    return Promise.resolve();
  }
  if (window.location.href.indexOf("member/editmobile") > -1) {
    return Promise.reject({ type: "active", name: "绑定手机" });
  }
  if (window.location.href.indexOf("/signPage/") > -1) {
    return Promise.reject({ type: "bindMobile", name: "绑定手机", icon: "icon-verification_phone", color: "#377BFE" });
  }
  let bindMobilePageFn = (item, url) => {
    // 判断是否符合场景页面
    if (window._activePageURL.indexOf(url) > -1) {
      return Promise.reject({ type: "bindMobile", name: "绑定手机", icon: "icon-verification_phone", color: "#377BFE" });
    }
  };
  if (is_bind_mobile == 1) {
    if (window.location.href.indexOf("/member/scaneditmobile") >= 0) {
      window.localStorage.setItem("is_force_mobile", 999);
    }
    return Promise.reject({ type: "bindMobile", name: "绑定手机", icon: "icon-verification_phone", color: "#377BFE" });
  } else if (is_bind_mobile == 2) {
    for (const item of bind_mobile_page) {
      switch (item) {
      case "member_center":
        await bindMobilePageFn(item, "/member?");
        break;
      case "goods_detail":
        await bindMobilePageFn(item, "/goods/");
        await bindMobilePageFn(item, "/groups/");
        break;
      case "promotion_center":
        await bindMobilePageFn(item, "/member/extension?");
        break;
      }
    }
    return Promise.resolve();
  }
}

// 实名认证
function bindRealName(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  // 定义排除的 URL。
  const excludedUrls = ["/personBank", "/signCompany", "/member/orderpay/auth/"];
  // 检查当前 URL 是否被排除。
  const currentUrl = window.location.href;
  if (excludedUrls.some(url => currentUrl.includes(url))) {
    return Promise.reject({ type: "active", name: "实名认证" });
  }
  // 检查实名认证插件是否开启并且需要进行认证。
  const isOpen = data.real_name_auth_is_open === 1;
  const needsAuth = data.is_auth !== 1 && data.real_name_auth_scene?.length > 0;
  if (isOpen && needsAuth) {
    if (data.real_name_auth_scene.indexOf("1") > -1 && currentUrl.indexOf("/personBank") < 0)
      return Promise.reject({ type: "bindRealName", name: "实名认证", icon: "icon-fontclass-wdeguanzhu", color: "#377BFE" });

    // 定义需要实名认证的场景 URL。
    const scenarioUrls = {
      2: ["/member/withdrawal?"],
      3: ["/videoAgreement?", "/releaseVideo?"],
      4: ["/microRelease?"],
      5: ["/member/extension?"],
      6: ["/member/supplier?"],
      7: ["/o2o/storeApply?"],
      8: ["/hotel/apply?"],
      9: ["/anchorApply?"]
    };
    // 检查当前 URL 是否匹配任何场景 URL。
    const needsRealName = data.real_name_auth_scene.some(scene => {
      const urls = scenarioUrls[scene] ?? [];
      return urls.some(url => window._activePageURL.includes(url));
    });
    if (needsRealName) {
      // 需要进行实名认证，跳转至实名认证页面。
      return Promise.reject({ type: "bindRealName", name: "实名认证", icon: "icon-fontclass-wdeguanzhu", color: "#377BFE" });
    }
  }
  // 实名插件未开启或已实名认证过，直接下一步
  return Promise.resolve();
}

// 绑定地址
function setAddress({ is_login, bind_address: { bind_address_type, bind_address_page, is_bind_address } }) {
  if (is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if (is_bind_address === 1) return Promise.resolve();

  const excludedUrls = ["/member/address", "/member/appendAddress", "/login"]; //当前链接符合该数组条件，拦截但不处理
  if (excludedUrls.some(url => window.location.href.includes(url))) {
    return Promise.reject({ type: "active", name: "绑定地址" });
  }

  const pageUrls = {
    member_center: "/member?",
    goods_detail: ["/goods/", "/groups/"],
    promotion_center: "/member/extension?"
  };
  const isBindPage = pageUrl => (Array.isArray(pageUrl) ? pageUrl.some(url => window._activePageURL.includes(url)) : window._activePageURL.includes(pageUrl));
  const isBindAddressPage = bind_address_type === 2 && bind_address_page.some(pageName => isBindPage(pageUrls[pageName]));

  if (bind_address_type === 1) return Promise.reject({ type: "setAddress", name: "绑定地址", icon: "icon-icon_location", color: "#29D99F" }); //全局绑定
  if (isBindAddressPage) return Promise.reject({ type: "setAddress", name: "绑定地址", icon: "icon-icon_location", color: "#29D99F" }); //指定页面
  return Promise.resolve();
}

// 默认上传视频（需要上传过视频才可进入视频）
function uploadVideo(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if (window.location.href.indexOf("/releaseVideo") > -1) {
    return Promise.reject({ type: "active", name: "发布视频" });
  }
  if (data?.need_video && window.location.href.indexOf("/releaseVideo") <= -1) {
    return Promise.reject({ type: "uploadVideo", name: "发布视频", icon: "icon-fontclass-ship", color: "#29D99F" });
  }
  return Promise.resolve();
}
function carBind(data){
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if(data?.force_bind_car && window.location.href.indexOf("/carBind") > -1){
    return Promise.reject({ type: "active", name: "绑定车牌" });
  }
  if(data?.force_bind_car && window.location.href.indexOf("/carBind") <= -1 ){
    return Promise.reject({ type: "carBind", name: "绑定车牌", icon: "icon-chepaihao", color: "#29D99F" });
  }
  return Promise.resolve();
}

// 新客下单
function levelCompel(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  const excludedUrls = ["/levelCompel", "/member/orderpay/", "/order/pay_back/", "/login"]; //当前链接符合该数组条件，拦截但不处理
  if (excludedUrls.some(url => window.location.href.includes(url))) {
    return Promise.reject({ type: "active", name: "新客下单" });
  }
  let isLevel = data?.is_level_compel && data.is_level_compel == 1;
  if (isLevel && window.location.href.indexOf("member/orderpay") <= -1 && window.location.href.indexOf("/order/pay_back") <= -1) {
    return Promise.reject({ type: "levelCompel", name: "新客下单", icon: "icon-qt_button_groupbbuy", color: "#29D99F" });
  }
  return Promise.resolve();
}

// 话费充值 -- #19217
function phoneBillRecharge(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if (window.location.href.indexOf("/recharge_phone_bill/recharge_phone_bill") > -1) {
    return Promise.reject({ type: "active", name: "绑卡开卡" });
  }
  if (!phone_bill_recharge_type) {
    return Promise.resolve();//已经弹过
  }
  // 满足phone_bill_recharge_member条件而且是在登陆后触发
  if (data && data.phone_bill_recharge_member && data.phone_bill_recharge_member.status == 1 && data.is_login == 1) {
    return Promise.reject({ type: "phoneBillRecharge", name: "绑卡开卡", icon: "icon-qt_button_groupbbuy", color: "#29D99F" });
  }
  return Promise.resolve();
}
// #32329 如用户有待签署的合同时，无法进入会员中心和推广中心，弹出提示,点击“去签署”，则跳转到待签署的合同列表。
function signContract(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  const excludedUrls = ["/contractList", "/signBusiness", "/signPage"]; //当前链接符合该数组条件，拦截但不处理
  if (excludedUrls.some(url => window.location.href.includes(url))) {
    return Promise.reject({ type: "active", name: "合同签署" });
  }
  // 定义需要签署的场景
  const needSignUrls = ["/member", "/member/extension",'/usr/missionCenter'];
  // 检查当前 URL 是否匹配到指定场景 URL。
  const isNeedSignUrls = needSignUrls.some(url => window.location.href.includes(url));

  if (isNeedSignUrls && data?.shop_contract && data?.shop_contract.member_center_status && data?.shop_contract.contract_id) {
    return Promise.reject({ type: "signContract", name: "合同签署", icon: "icon-fontclass-gerenyinzhang", color: "#ee0a24" });
  }
  return Promise.resolve();
}

export { unfinishedTaskFn, redirectToPage };
